package com.hxy.security;

import com.hxy.entity.AuthUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;


/**
 * 自定义API，基于角色权限的鉴权管理
 */
@Component(value = "rbacConfig")
@Slf4j
public class RbacConfig {

    /**
     * 判断是否拥有操作权限
     *
     * @return
     */
    public boolean hasPermission(Authentication authentication, HttpServletRequest request) {
        log.info(">>>>>>>>>判断是否有操作权限");
        log.info(">>>>>>>>>>>" + authentication);

        // 先判断是否登录
        Object principal = authentication.getPrincipal();
        log.info(principal.toString());

        if (principal.equals("anonymousUser")) {
            return false;
        } else {
            AuthUser authUser = (AuthUser) principal;
            String uri = request.getRequestURI();
            log.info(uri);

            // 根据登录用户获取角色权限信息
            // 权限判断
            // 查询用户角色是否有操作权限
            String modelPaths = "auth,fruits,jsr"; // 从数据库中查询用户的操作权限
            String one = uri.substring(1, uri.indexOf("/",1));
            Boolean contains = modelPaths.contains(one);
            log.info(one);
            log.info(contains.toString());

            if(contains){
                return true;
            }
            return false;
        }
    }

}
